package cn.gorit.content.service.impl;

import cn.gorit.common.enums.ResultEnums;
import cn.gorit.common.exception.BlogException;
import cn.gorit.common.lang.Result;
import cn.gorit.content.service.CommentService;
import cn.gorit.dto.content.BlogUpdateDto;
import cn.gorit.entity.content.Comment;
import cn.gorit.entity.content.CommentResponse;
import cn.gorit.mapper.content.BlogMapper;
import cn.gorit.utils.IdWorker;
import cn.gorit.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * @version v1.0
 * @Classname CommentServiceImpl
 * @Description 评论实现的接口
 * @Author CodingGorit
 * @Created on 2021/4/3 16:42
 * @IDLE IntelliJ IDEA
 **/
@Service
public class CommentServiceImpl implements CommentService {

//    @Autowired
//    private CommentDao commentDao;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private IdWorker idWorker;

    // 保存评论的接口，添加或者更新
    @Override
    public Result<Object> save(Comment comment) {
//        String userId = comment.getComment_user_id();
        // 查询用户信息，并填充
        //        comment.setComment_user_nickname("xxx");
        comment.setComment_id(UUID.randomUUID().toString().replace("-",""));
        template.insert(comment);
        // 保存评论的接口，同时更新 blog 的 评论 数量
        BlogUpdateDto dto = blogMapper.getBlogUpdate(comment.getComment_blog_id());
        dto.setBlogComment(dto.getBlogComment() + 1);
        blogMapper.updateBlogComment(dto);
        // 重复的情况呢？
        return new Result<>(ResultEnums.ADD_SUCCESS.getCode(),ResultEnums.ADD_SUCCESS.getMsg());
    }

    @Override
    public Result<Object> update(Comment comment) {
        // 参数校验
        if (comment.getComment_id() == null)
            return new Result<>(ResultEnums.UPDATE_FAILED.getCode(),"缺少 comment_id 参数");
        // 修改 comment
        Query query = new Query(Criteria.where("comment_id").is(comment.getComment_id()));
        Update update = new Update();
        update.set("comment_content",comment.getComment_content());
        // 修改子评论，
        if (comment.getResponse().size() != 0)
            update.set("response",comment.getResponse());
        template.upsert(query, update,Comment.class);
        return new Result<>(ResultEnums.UPDATE_SUCCESS.getCode(),ResultEnums.UPDATE_SUCCESS.getMsg());
    }

    // 查询评论相关的接口, 只查询和当前 blogId 绑定的接口
    @Override
    public Result<List<Comment>> getComments(String blogId) {
        // 根据 blog_id 来查询评论列表
        Query query = new Query(Criteria.where("comment_blog_id").is(blogId));
        List<Comment> list = template.find(query,Comment.class);
        return new Result<>(ResultEnums.QUERY_SUCCESS.getCode(),ResultEnums.QUERY_SUCCESS.getMsg(),list);
    }

    // 评论回复
    @Override
    public Result<Object> responseComment(CommentResponse responses) {
        // 根据父类 id，查询得到 Comment，并添加至 response 列表中
        responses.setResponse_id(UUID.randomUUID().toString().replace("-",""));
        Query query = new Query(Criteria.where("comment_id").is(responses.getComment_id()));
        Comment comment = template.findOne(query,Comment.class);
        if (comment != null) {
            List<CommentResponse> list = comment.getResponse();
            list.add(responses);
            comment.setResponse(list);
            Update update = new Update();
            update.set("response",list);
            template.upsert(query, update,Comment.class);
            return new Result<>("回复成功");
        }
        return new Result<>("回复失败");
    }
    // 判断删除的是子评论 还是 父评论
    @Override
    public void delete(String commentId, String responseId) {
        // 如果只有 commentId，就是删除父评论
        Query query = new Query(Criteria.where("comment_id").is(commentId));
        Comment comment = template.findOne(query,Comment.class);
        try {
            if (StringUtils.isBlank(responseId) && StringUtils.isNotBlank(commentId)) {
                assert comment != null;
                String blogId = comment.getComment_blog_id();
                template.remove(query,Comment.class);
                BlogUpdateDto dto = blogMapper.getBlogUpdate(blogId);
                if (dto.getBlogComment() <= 0) {
                    return;
                }
                dto.setBlogComment(dto.getBlogComment() - 1);
                blogMapper.updateBlogComment(dto);
            }

            // 如果有 responseId  更新操作
            if (StringUtils.isNotBlank(commentId) && StringUtils.isNotBlank(responseId)) {
                List<CommentResponse> response = comment.getResponse();
                response.removeIf(res -> res.getResponse_id().equals(responseId));
                comment.setResponse(response);
                template.upsert(query, new Update().set("response",response),Comment.class);
            }
        } catch (Exception e) {
            throw new BlogException("评论更新失败");
        }
    }

    // 点赞评论  todo

}
